import Router from 'koa-router'
import { serviceConfig } from '../serviceConfig'
import mq from '../mysql'
import { getTime, checkLogin, routerBottom,STR } from '../utils'
const dayjs = require('dayjs')

const staticBasePath = `${serviceConfig.domainName}:${serviceConfig.localhost}/webimg/`
const router = new Router()
router.post(
  '/addBlog',
  async (ctx, next) => {
    const { content, title, cover } = ctx.request.body
    try {
      await mq(`
      INSERT INTO blog (
        creationTime,
        content,
        cover,
        title
      ) VALUES (
        '${getTime()}',
        '${STR.stringify(content)}',
        '',
        '${title}'
      )
    `)
    } catch (err) {
      console.log('adderr', err)
    }
    next()
  },
  routerBottom
)
router.post(
  '/getBlogList',
  async (ctx, next) => {
    const { pageNum, size } = ctx.request.body
    try {
      const list = await mq(
        `SELECT * FROM blog WHERE  showStatus = 0 ORDER BY creationTime DESC LIMIT ${
          pageNum * size
        },${size}`
      )
      list.forEach((el: any) => {
        el.creationTime = dayjs(el.creationTime).valueOf()
        if (el.viewCount === null) {
          el.viewCount = 0
        }
      })
      ctx.params.body = {
        status: true,
        data: list,
      }
      next()
    } catch (error) {
      console.log(error)
    }
  },
  routerBottom
)

router.post(
  '/getBlogDetail',
  async (ctx, next) => {
    const { blogId } = ctx.request.body
    let blogs = await mq(`
  SELECT * FROM blog WHERE blogId=${blogId} AND showStatus = 0
`)
    if ((<any[]>blogs).length === 0) {
      ctx.params.body = {
        status: false,
        msg: '未查询到数据',
      }
      next()
    } else {
      let blog = (<any[]>blogs)[0]
      blog.content = STR.parse(blog.content)
      if (blog.viewCount === null) {
        blog.viewCount = 0
      }
      blog.commentList =
        (await mq(
          `SELECT * FROM comment WHERE blogId = ${blogId} AND showStatus = 0 ORDER BY creationTime DESC`
        )) || []
      if (blog.commentList.length > 0) {
        for (const el of blog.commentList)
          el.creationTime = dayjs(el.creationTime).valueOf()
      }
      ctx.params.body = {
        status: true,
        data: {
          ...blog,
          creationTime: dayjs(blog.creationTime).valueOf(),
        },
      }
      next()
      // 浏览量++
      mq(
        `UPDATE blog SET viewCount = '${
          blog.viewCount + 1
        }' WHERE blogId = ${blogId}`
      )
    }
  },
  routerBottom
)

router.post(
  '/queryBlog',
  async (ctx, next) => {
    const { searchText } = ctx.request.body
    const blogs = await mq(`
    SELECT blogId,title,content FROM blog WHERE title LIKE '%${searchText}%' AND content LIKE '%${searchText}%'
    `)
    let data: { id: number; content: string }[] = []

    if ((<any[]>blogs).length !== 0) {
      ;(<any[]>blogs).map((el) => {
        data.push({
          id: el.blogId,
          content: el.title,
        })
      })
    }
    ctx.params.body = {
      status: true,
      data,
    }
    next()
  },
  routerBottom
)

router.post(
  '/addComment',
  async (ctx, next) => {
    const { status, msg, data: info } = await checkLogin(ctx)
    if (!status) {
      ctx.params.body = {
        status,
        msg,
      }
      next()
      return
    }
    const { content, id } = ctx.request.body
    const insertInfo = await mq(`
      INSERT INTO comment(
        blogId,content,creationTime,name
      ) VALUES (
        '${id}',
        '${content}',
        '${getTime()}',
        '${info!.name}'
      )
    `)
    ctx.params.body = {
      status: true,
      data: {
        userName: info!.name,
        commentId: insertInfo.insertId,
      },
    }
    next()
  },
  routerBottom
)

router.post(
  '/queryComment',
  async (ctx, next) => {
    const { pageNum, size } = ctx.request.body
    try {
      const comment = await mq(`select comment.*,blog.title as blogTitle FROM comment,blog where blog.blogId = comment.blogId and comment.showStatus=0 and blog.showStatus=0 limit ${
        pageNum * size
      },${size}

    `)
      if (comment.length > 0) {
        for (const el of <any[]>comment) {
          el.creationTime = dayjs(el.creationTime).valueOf()
          el.replyTime = dayjs(el.replyTime).valueOf()
        }
      }
      ctx.params.body = {
        status: true,
        data: comment,
      }
      next()
    } catch (error) {
      console.log(error)
    }
  },
  routerBottom
)

router.post(
  '/deleteBlog',
  async (ctx, next) => {
    try {
      const { blogId } = ctx.request.body

      const blogs = await mq(`
SELECT blogId FROM blog WHERE blogId = ${blogId}  AND showStatus = 0
`)
      if ((<any[]>blogs).length === 0) {
        ctx.params.body = {
          status: false,
          msg: '不存在该数据',
        }
        next()
      } else {
        await mq(`UPDATE blog SET showStatus = 1 WHERE blogId = ${blogId}`)
        ctx.params.body = {
          status: true,
        }
        next()
      }
    } catch (error) {
      console.log(error)
    }
  },
  routerBottom
)

router.post(
  '/deleteComment',
  async (ctx, next) => {
    const commentIds = ctx.request.body
    const comments = await mq(
      `SELECT commentId FROM comment WHERE commentId in (${commentIds})  AND showStatus = 0`
    )
    if ((<any[]>comments).length === 0) {
      ctx.params.body = {
        status: false,
        msg: '不存在该数据',
      }
      next()
    } else {
      await mq(
        `UPDATE comment SET showStatus = 1 WHERE commentId in (${commentIds})`
      )
      ctx.params.body = {
        status: true,
      }
      next()
    }
  },
  routerBottom
)

router.post(
  '/addCommentReply',
  async (ctx, next) => {
    const { reply, commentId } = ctx.request.body
    await mq(
      `UPDATE comment SET reply = '${reply}',replyTime = '${getTime()}' WHERE commentId = ${commentId}`
    )
    next()
  },
  routerBottom
)

router.post(
  '/deleteCommentReply',
  async (ctx, next) => {
    const { commentId } = ctx.request.body
    await mq(
      `UPDATE comment SET reply = '',replyTime = null WHERE commentId = ${commentId}`
    )
    next()
  },
  routerBottom
)

router.post(
  '/getTotalCommentStatus',
  async (ctx, next) => {
    const count = await mq(
      `SELECT COUNT(*) AS count FROM comment WHERE viewStatus = 0`
    )
    let count2 = (<{ count: number }[]>count)[0].count
    ctx.params.body = { status: true, data: count2 }
    next()
  },
  routerBottom
)
router.post(
  '/changeCommentViewStatus',
  async (ctx, next) => {
    const { commentIds } = ctx.request.body
    await mq(
      `UPDATE comment SET viewStatus = 1 WHERE commentId in (${commentIds})`
    )
    next()
  },
  routerBottom
)
export default router
